package cn.openea.perpartner.expert.web.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.openea.perpartner.common.core.text.Convert;
import cn.openea.perpartner.common.core.utils.DateUtils;
import cn.openea.perpartner.expert.web.domain.dto.MsgDto;
import cn.openea.perpartner.expert.web.domain.entity.Delivery;
import cn.openea.perpartner.expert.web.domain.entity.ExpertJob;
import cn.openea.perpartner.expert.web.service.IDeliveryService;
import cn.openea.perpartner.expert.web.service.IExpertJobService;
import cn.openea.perpartner.expert.web.service.ISendMsgService;
import cn.openea.perpartner.meily.web.entity.Todo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.TimerTask;

/**
 * @author Weird077
 * @description TODO
 * @date 2023-07-04 10:53
 */
@Slf4j
@Service("expertSendMsgService")
public class SendMsgServiceImpl implements ISendMsgService {
    @Value("${common.uri}")
    private String sendMsgUri;
    @Value("${sso.url}")
    private String ssoUri;
    @Value("${meily.header.sysid}")
    private String sysId;
    @Value("${meily.header.syspwd}")
    private String sysPwd;
    @Resource
    private IExpertJobService expertJobService;
    @Resource
    private IDeliveryService deliveryService;
    /**
     * 工单进度通知
     */
    private static final String WORKER_PROGRESS_TIP = "Zx2oCUdXO6VTXu_QddXdEZ-N8co5Z8UsudzFP6lbSEs";
    /**
     * 新需求推送通知
     */
    private static final String NEW_CHANCE_TIP = "dELdPIqv4GrN8q5Jl8WQpXElzDDjZKuvx_u3MSwx1Es";

    @Override
    public TimerTask publishJob(ExpertJob job) {
        return null;
    }

    @Override
    public TimerTask partnerSignup(MsgDto dto) {
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "收到" + getNickName(dto.getPartnerId()) + "报名参与" + dto.getSubject() + "项目的申请，请尽快进行初选！");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", "待初选");
        object.put("keyword3", getNickName(dto.getUserId()));
        object.put("pagepath", dto.getMinAppUri());
        object.put("url", "/pages_private_scene1/ExpertCooperate/jobInfo?taskNumber=" + dto.getTaskNum());
        object.put("remark", "点击查看报名信息！【温馨提示】初选结束后将进入复选环节，其他拍档将无法报名，需慎重操作哦！");
        object.put("userid", dto.getUserId());
        object.put("docUnid", dto.getTaskId());
        object.put("createdUserid", dto.getPartnerId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask userPreselect(Todo todo) {
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "恭喜您，经" + getNickName(todo.getPrvUserId()) + "的资料核对，您具备参与" + todo.getSubject() + "项目的资格，进入本项目的复选环节，请在24小时内确认是否参与！");
        object.put("keyword1", todo.getReqNumber());
        object.put("keyword2", "通过初选");
        object.put("keyword3", getNickName(todo.getUserId()));
        object.put("pagepath", todo.getMinAppUri());
        object.put("url", "/pages_private_scene1/ExpertCooperate/jobInfo?taskNumber=" + todo.getReqNumber());
        object.put("remark", "点击查看复选通知！【温馨提示】务必在24小时内回复，逾期将视为放弃资格。");
        object.put("userid", todo.getUserId());
        object.put("docUnid", todo.getTaskId());
        object.put("createdUserid", todo.getPrvUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask partnerReselect(Todo todo) {
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "收到" + getNickName(todo.getPrvUserId()) + "参与" + todo.getSubject() + "项目的复选申请，请尽快进行复选！");
        object.put("keyword1", todo.getReqNumber());
        object.put("keyword2", "待复选");
        object.put("keyword3", getNickName(todo.getUserId()));
        object.put("pagepath", todo.getMinAppUri());
        object.put("url", "/pages_private_scene1/ExpertCooperate/jobInfo?taskNumber=" + todo.getReqNumber());
        object.put("remark", "点击查看复选信息！【温馨提示】请尽快完成复选");
        object.put("userid", todo.getUserId());
        object.put("docUnid", todo.getTaskId());
        object.put("createdUserid", todo.getPrvUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask userReselect(Todo todo) {
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "恭喜您，经" + getNickName(todo.getPrvUserId()) + "的最终筛选，您的各项指标都非常适合成为" + todo.getSubject() + "项目的最佳拍档，项目即将启动，请您在24小时内确认是否参与！");
        object.put("keyword1", todo.getReqNumber());
        object.put("keyword2", "已中标");
        object.put("keyword3", getNickName(todo.getUserId()));
        object.put("pagepath", todo.getMinAppUri());
        object.put("url", "/pages_private_scene1/ExpertCooperate/jobInfo?taskNumber=" + todo.getReqNumber());
        object.put("remark", "点击查看中标通知！【温馨提示】务必在24小时内回复，逾期将视为放弃资格。");
        object.put("userid", todo.getUserId());
        object.put("docUnid", todo.getTaskId());
        object.put("createdUserid", todo.getPrvUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask userReselectReject(MsgDto dto) {
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "很遗憾，经" + getNickName(dto.getUserId()) + "的最终筛选，已在候选人中确定了" + dto.getSubject() + "项目的最佳拍档，期待下次的合作！");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", "不通过");
        object.put("keyword3", getNickName(dto.getPartnerId()));
        object.put("url", dto.getMinAppUri());
        object.put("pagepath", dto.getMinAppUri());
        object.put("remark", "为了下次能匹配到更精准的工作机会，建议您前往【隐私】完善资料！");
        object.put("userid", dto.getPartnerId());
        object.put("createdUserid", dto.getUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask partnerConfirm(Todo todo) {
        ExpertJob job = expertJobService.getByTaskNum(todo.getReqNumber());
        int count = job.getPaymentType().split(":").length;
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", getNickName(todo.getPrvUserId()) + "已确认参与" + todo.getSubject() + "项目，项目已启动，第1期（1/" + count + "）将在" + job.getDeliveryDate() + "前进行验收，请耐心等候项目成果！");
        object.put("keyword1", todo.getReqNumber());
        object.put("keyword2", "项目进行中");
        object.put("keyword3", getNickName(todo.getUserId()));
        object.put("pagepath", "/pages_private_scene1/ExpertCooperate/partnerWorkPlan?taskNumber=" + todo.getReqNumber() + "&pubPlan=1");
        object.put("url", "/pages_private_scene1/ExpertCooperate/partnerWorkPlan?taskNumber=" + todo.getReqNumber() + "&pubPlan=1");
        object.put("remark", "点击查看项目实施计划！【温馨提示】项目顺利完成后，平台需从项目款中抽取3%作为本次项目的服务费，请知晓！");
        object.put("userid", job.getCreateUser());
        object.put("docUnid", todo.getTaskId());
        object.put("createdUserid", todo.getPrvUserId());
        return sendMsgToApplets(object);
    }


    @Override
    public TimerTask userPreselectReject(MsgDto dto) {
        JSONObject object = new JSONObject();
        String nickName = getNickName(dto.getUserId());
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "很遗憾，经" + nickName + "的资料核对，您与本次" + dto.getSubject() + "项目的匹配度不高，期待下次的合作机会！");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", "不通过");
        object.put("keyword3", "平台");
        object.put("pagepath", dto.getMinAppUri());
        object.put("url", dto.getMinAppUri());
        object.put("remark", "为了下次能匹配到更精准的工作机会，建议您前往【隐私】完善资料！");
        object.put("userid", dto.getPartnerId());
        object.put("createdUserid", dto.getUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask userEvaluate(MsgDto dto) {
        JSONObject object = new JSONObject();
        String nickName = getNickName(dto.getUserId());
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", "感谢您的评价与宝贵建议，欢迎您再次使用最佳拍档工作平台！");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", "已完结");
        object.put("keyword3", nickName);
        object.put("pagepath", dto.getMinAppUri());
        object.put("url", dto.getMinAppUri());
        object.put("userid", dto.getUserId());
        object.put("createdUserid", dto.getUserId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask partnerSubmitResult(MsgDto dto) {
        Delivery delivery = deliveryService.getById(dto.getDeliveryId());
        int retryCount = Convert.toInt(delivery.getReturnNum());
        int subTaskSortNum = Convert.toInt(delivery.getSubTaskSortNum());
        int totalPeriods = Convert.toInt(delivery.getTotalPeriods());
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", getNickName(dto.getPartnerId()) + "已提交" + delivery.getWorkSubject() + "项目的第" + subTaskSortNum + "期（" + subTaskSortNum + "/" + totalPeriods + "）成果，请前往验收！ ");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", retryCount > 0 ? "第" + retryCount + "次修改" : "验收成果");
        object.put("keyword3", getNickName(dto.getUserId()));
        object.put("pagepath", dto.getMinAppUri());
        object.put("url", "/pages_process2/ExpertCooperate/AcceptanceResults?taskNumber=" + dto.getTaskNum() + "&PartnerName=" + getNickName(dto.getPartnerId()));
        object.put("remark", "点击验收成果！【温馨提示】为了不耽误项目总进度，请尽快完成验收！");
        object.put("userid", dto.getUserId());
        object.put("createdUserid", dto.getPartnerId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask rejectResult(MsgDto dto) {
        Delivery delivery = deliveryService.getById(dto.getDeliveryId());
        int retryCount = Convert.toInt(delivery.getReturnNum());
        int subTaskSortNum = Convert.toInt(delivery.getSubTaskSortNum());
        int totalPeriods = Convert.toInt(delivery.getTotalPeriods());
        JSONObject object = new JSONObject();
        object.put("templateid", WORKER_PROGRESS_TIP);
        object.put("first", delivery.getWorkSubject() + "项目的第" + subTaskSortNum + "期（" + subTaskSortNum + "/" + totalPeriods + "）成果未能通过验收，现在进行第" + retryCount + "次返修，请按照用户要求进行修改！");
        object.put("keyword1", dto.getTaskNum());
        object.put("keyword2", "第" + retryCount + "次返修");
        object.put("keyword3", getNickName(dto.getPartnerId()));
        object.put("pagepath", dto.getMinAppUri());
        object.put("url", "/pages_process2/ExpertCooperate/partnerWorkPlan?taskNumber=" + dto.getTaskNum() + "&pubPlan=1");
        object.put("remark", "点击修改工作成果！【非常重要】您只有2次返修机会，每一次的返修都将影响到用户对工作成果的满意度，请谨慎提交。");
        object.put("userid", dto.getUserId());
        object.put("createdUserid", dto.getPartnerId());
        return sendMsgToApplets(object);
    }

    @Override
    public TimerTask userVerifyResult(MsgDto dto) {
        try {
            Delivery delivery = deliveryService.getById(dto.getDeliveryId());
            String deliveryDate = DateUtils.formatDate(delivery.getDeliveryDate(), "yyyy-MM-dd");
            String today = DateUtils.formatDate(DateUtils.getNow(), "yyyy-MM-dd");
            int diff = (int) DateUtil.between(DateUtils.parseDate(deliveryDate), DateUtils.parseDate(today), DateUnit.DAY);
            int actualPrice = Convert.toInt(delivery.getActualPrice());
            int subTaskSortNum = Convert.toInt(delivery.getSubTaskSortNum());
            int totalPeriods = Convert.toInt(delivery.getTotalPeriods());
            JSONObject object = new JSONObject();
            object.put("templateid", WORKER_PROGRESS_TIP);
            object.put("first", getNickName(dto.getUserId()) + "已完成" + delivery.getWorkSubject() + "项目的第" + subTaskSortNum + "期（" + subTaskSortNum + "/" + totalPeriods + "）成果验收，本期佣金" + actualPrice + "元已发放至钱包！");
            object.put("keyword1", dto.getTaskNum());
            object.put("keyword2", "平台");
            object.put("keyword3", getNickName(dto.getPartnerId()));
            object.put("pagepath", "/pages_process2/ExpertCooperate/AcceptanceResults?taskNumber=" + dto.getTaskNum() + "&PartnerName=" + getNickName(dto.getPartnerId()));
            object.put("url", "/pages_process2/ExpertCooperate/AcceptanceResults?taskNumber=" + dto.getTaskNum() + "&PartnerName=" + getNickName(dto.getPartnerId()));
            object.put("remark", diff > 0 ? "【温馨提示】当前项目已超时" + diff + "天，为了不影响项目总进度，需加快工作步伐！" : "点击查看验收结果");
            object.put("userid", dto.getUserId());
            object.put("createdUserid", dto.getPartnerId());
            return sendMsgToApplets(object);
        } catch (Exception e) {
            log.error("用户验收结果通知失败", e);
        }
        return null;
    }

    /**
     * 发送消息到小程序
     */
    private TimerTask sendMsgToApplets(JSONObject object) {
        JSONObject params = new JSONObject();
        params.put("templateid", object.getString("templateid"));
        params.put("first", object.getString("first"));
        params.put("keyword1", object.getString("keyword1"));
        params.put("keyword2", object.getString("keyword2"));
        params.put("keyword3", object.getString("keyword3"));
        params.put("keyword4", object.getString("keyword4"));
        params.put("keyword5", object.getString("keyword5"));
        params.put("keyword6", object.getString("keyword6"));
        params.put("remark", object.getString("remark"));
        params.put("pagepath", object.getString("pagepath"));
        params.put("url", object.getString("url"));
        params.put("userid", object.getString("userid"));
        params.put("docUnid", object.getString("taskNum"));
        params.put("createdUserid", object.getString("createdUserid"));
        return new TimerTask() {
            @Override
            public void run() {
                HttpResponse response = HttpRequest.post(sendMsgUri + "/msg/savemsg")
                        .header("Content-Type", "application/json")
                        .header("Accept", "application/json")
                        .header("sysid", sysId)
                        .header("syspwd", sysPwd)
                        .body(params.toJSONString())
                        .execute();
                log.info("{}发送消息到小程序返回结果：{}", DateUtil.now(), response.body());
            }
        };
    }

    /**
     * 获取用户昵称
     */
    private String getNickName(String userId) {
        String result = HttpUtil.get(ssoUri + "/user/cache/" + userId);
        if (StrUtil.isNotBlank(result)) {
            JSONObject wxObject = JSON.parseObject(result);

            return wxObject.getJSONObject("data").getString("nickName");
        }
        return "";
    }
}
